<?php

/**
 * Typecho又拍云文件管理
 * 
 * @package UpyunFile
 * @author codesee
 * @version 0.6.0
 * @link http://pengzhiyong.com
 * @date 2014-01-15
 */

use \blog\libs\Common;
use \Qcloud\Cos\Client;

class Qcloudcos_Attachment {
	protected $config;
	protected $upyun;
	public function __construct($connect = TRUE) {
		$this->config = unserialize(Common::option('attachmentQcloudcos'));
		if (!class_exists(Client::class, FALSE)) {
			$root = str_replace('\\', '/', __DIR__) . '/';
			require('phar://'. $root .'/cos-sdk-v5-7.phar/vendor/autoload.php');
		}
		if ($connect) {
			$this->cos = new Client([
				'region' => $this->config['region'],
				'credentials'=> [
					'secretId' => $this->config['secret_id'],
					'secretKey' => $this->config['secret_key']
				]
			]);
		}
	}
	/**
	 * 获取From
	 * @return array
	 */
	public function getForm() {
		return [
			['show' => 'APPID', 'name' => 'appid', 'type' => 'text', 'val' => $this->config['appid']],
			['show' => 'SecretId', 'name' => 'secret_id', 'type' => 'text', 'val' => $this->config['secret_id']],
			['show' => 'SecretKey', 'name' => 'secret_key', 'type' => 'text', 'val' => $this->config['secret_key']],
			['show' => 'Bucket地域', 'name' => 'region', 'type' => 'text', 'val' => $this->config['region']],
			['show' => 'Bucket名称（不需要包含形似“-123456”的appid）', 'name' => 'bucket', 'type' => 'text', 'val' => $this->config['bucket']]
		];
	}
	/**
	 * 设置
	 * @access public
	 */
	public function config($config) {
		Common::option('attachmentQcloudcos', serialize($config));
	}
	/**
	 * 上传
	 * @access public
	 * @param string $local 本地文件
	 * @param string $remote 远程路径
	 * @return boolean
	 */
	public function upload($local, $remote) {
		//上传文件
		$fh = fopen($local, 'r');
		$this->cos->upload($this->config['bucket'] .'-'. $this->config['appid'], $remote, $fh, [
			"ACL" => 'public-read',
			'CacheControl' => 'private'
		]);
		@fclose($fh);
	}
	/**
	 * 删除文件
	 * @access public
	 * @param string $path 路径
	 * @return boolean
	 */
	public function delete($path) {
		return $this->cos->deleteObject([
			'Bucket' => $this->config['bucket'] .'-'. $this->config['appid'],
			'Key' => $path
		]);
	}
}
